import 'dart:async';

import 'package:crm/components/ui/loader.dart';
import 'package:crm/components/ui/mycard.dart';
import 'package:crm/enum/enum.dart';
import 'package:crm/model/login.dart';
import 'package:crm/routers/application.dart';
import 'package:crm/service/api_service.dart';
import 'package:crm/utils/styles.dart';
import 'package:crm/utils/theme_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  bool isDark = false;
  LoaderState state = LoaderState.Loading;
  Timer _timer;
  var item;
  List<int> getDataList() {
    List<int> list = [];
    for (int i = 0; i < 7; i++) {
      list.add(i);
    }
    return list;
  }

  int currentStep = 0;
  List<Step> steps = [
    Step(
        // Title of the Step
        title: Text('上班时间 9:00'),
        // Content, it can be any widget here. Using basic Text for this example
        content: Text("补卡"),
        state: StepState.editing,
        isActive: true),
    Step(
        title: Text("下班时间 18:00"),
        content: Text("补卡成功"),
        // You can change the style of the step icon i.e number, editing, etc.
        state: StepState.complete,
        isActive: true)
  ];
  void startTimer() {
    //设置 2 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面
      setState(() {
        state = LoaderState.Succeed;
        cancelTimer();
      });
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  void initState() {
    super.initState();
    print('初始化');
    _login();
    startTimer();
  }

  @override
  void dispose() {
    cancelTimer();
    super.dispose();
  }

  void _login() async {
    LoginModel data = await ApiService.login('Administrator', '1234');
    if (data != null) {
      print(data.data.lplantindex);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    isDark = ThemeUtils.isDark(context);
    print(isDark);
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
    return Scaffold(
        // backgroundColor: Colors.grey[200],
        body: LoaderContainer(
            contentView: NestedScrollView(
              headerSliverBuilder: _buildSliverAppBar,
              body: MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: ListView(
                  padding: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                  children: <Widget>[
                    _buildSliverGridCategory(),
                    _shijian('时间助手', '进入应用'),
                    _headerdate(context),
                    _dateAllList(),
                    _shujutongji(),
                    _stepper()
                  ],
                ),
              ),
            ),
            loaderState: state));
  }

  List<Widget> _buildSliverAppBar(
      BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        expandedHeight: 160.0,
        title: Text('首页'),
        floating: false,
        pinned: true,
        snap: false,
        automaticallyImplyLeading: false,
        backgroundColor: Colors.pink,
        flexibleSpace: FlexibleSpaceBar(
            centerTitle: true,
            collapseMode: CollapseMode.pin,
            background: Image.network(
              'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
              fit: BoxFit.cover,
            )),
      ),
    ];
  }

  Widget _buildSliverGridCategory() {
    return MyCard(
        child: Container(
      decoration: isDark
          ? null
          : BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 8, color: Colors.grey[100]),
              ),
            ),
      child: InkWell(
        onTap: () {},
        child: Container(
          padding: EdgeInsets.all(8.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Image.network(
                          'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
                          width: 60.0,
                          height: 60.0,
                          fit: BoxFit.cover),
                    ),
                    SizedBox(height: 5),
                    Text('客户')
                  ]),
              Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Image.network(
                          'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
                          width: 60.0,
                          height: 60.0,
                          fit: BoxFit.cover),
                    ),
                    SizedBox(height: 5),
                    Text('商机')
                  ]),
              Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Image.network(
                          'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
                          width: 60.0,
                          height: 60.0,
                          fit: BoxFit.cover),
                    ),
                    SizedBox(height: 5),
                    Text('项目')
                  ]),
              Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Image.network(
                          'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
                          width: 60.0,
                          height: 60.0,
                          fit: BoxFit.cover),
                    ),
                    SizedBox(height: 5),
                    Text('数据')
                  ])
            ],
          ),
        ),
      ),
    ));
  }

  Widget _shijian(String left, String right) {
    return MyCard(
        child: Container(
      padding: EdgeInsets.all(15.0),
      decoration: isDark
          ? null
          : BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 1, color: Colors.grey[100]),
              ),
            ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            '$left',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(35), fontWeight: FontWeight.bold),
          ),
          Text('$right'),
        ],
      ),
    ));
  }

  int _index = 0;
  Widget _date(int text, int index) {
    return Container(
      width: ScreenUtil().setWidth(102),
      decoration: index == _index
          ? BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 1, color: Colors.green),
              ),
            )
          : null,
      child: InkWell(
        onTap: () {
          setState(
            () {
              _index = index;
              Application.router.navigateTo(context, '/timehelper');
            },
          );
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '日',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(30),
              ),
            ),
            SizedBox(
              height: 5.0,
            ),
            Text(
              '${text + 20}',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(30),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _headerdate(BuildContext context) {
    List<int> datas = getDataList();
    return MyCard(
      child: Container(
        height: ScreenUtil().setHeight(150),
        width: ScreenUtil().setWidth(750),
        decoration: isDark
            ? null
            : BoxDecoration(
                border: Border(
                  bottom: BorderSide(width: 1, color: Colors.grey[100]),
                ),
              ),
        child: ListView.builder(
          scrollDirection: Axis.horizontal, // 水平listView
          itemCount: datas.length,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return _date(datas[index], index);
          },
        ),
      ),
    );
  }

  List listData = ["第一条数据", "第二条数据", "第三条数据"];
  List<Widget> _listView() {
    return listData
        .map(
          (item) => Container(
            height: ScreenUtil().setHeight(100),
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Icon(Icons.calendar_today),
                ),
                Expanded(
                  flex: 5,
                  child: Text('$item'),
                ),
                Text(
                  '2020-06-03',
                  style: TextStyles.textGray12,
                )
              ],
            ),
          ),
        )
        .toList();
  }

  Widget _dateAllList() {
    return MyCard(
        child: Container(
      decoration: isDark
          ? null
          : BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 8, color: Colors.grey[100]),
              ),
            ),
      padding: EdgeInsets.only(right: 10.0),
      child: Column(
        children: <Widget>[
          Column(
            children: _listView(),
          ),
          Container(
            padding: EdgeInsets.only(bottom: 10.0),
            child: Text(
              '新建',
              style: TextStyle(
                color: Colors.blue,
                fontSize: ScreenUtil().setSp(40),
              ),
            ),
          )
        ],
      ),
    ));
  }

  Widget _shujutongji() {
    return Container(
      decoration: isDark
          ? null
          : BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 8, color: Colors.grey[100]),
              ),
            ),
      child: Column(
        children: <Widget>[
          _shijian('数据统计', '今天'),
          MyCard(
              child: Container(
            padding: EdgeInsets.fromLTRB(15.0, 10.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text('新增客户'),
                      SizedBox(
                        height: 3.0,
                      ),
                      Text(
                        '32',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(35),
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text('新增客户'),
                      SizedBox(
                        height: 3.0,
                      ),
                      Text(
                        '32',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(35),
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ))
        ],
      ),
    );
  }

  Widget _stepper() {
    return Container(
      // decoration: BoxDecoration(color: Colors.white),
      child: Column(
        children: <Widget>[
          _shijian('打卡签到', '进入打卡系统'),
          MyCard(
              child: Stepper(
            physics: NeverScrollableScrollPhysics(),
            currentStep: this.currentStep,
            steps: steps,
            type: StepperType.vertical,
            onStepTapped: (step) {
              setState(() {
                currentStep = step;
              });
              print("onStepTapped : " + step.toString());
            },
            onStepCancel: () {
              setState(() {
                if (currentStep > 0) {
                  currentStep = currentStep - 1;
                } else {
                  currentStep = 0;
                }
              });
              print("onStepCancel : " + currentStep.toString());
            },
            onStepContinue: () {
              setState(
                () {
                  if (currentStep < steps.length - 1) {
                    currentStep = currentStep + 1;
                  } else {
                    currentStep = 0;
                  }
                },
              );
              print("onStepContinue : " + currentStep.toString());
            },
          ))
        ],
      ),
    );
  }
}
